# Support script for setup.py
# - List available and valid themes by key (theme dir name)
# - Compile theme resource
# - Get list of all theme files

import os
import sys
import argparse
import pathlib


# This makes it so that it should be executed from searx-qt source root:
# python utils/themes_tool.py
pwd = str(pathlib.Path().resolve())
sys.path.insert(0, pwd)
from searxqt.themes import Themes  # noqa: E402


THEMES_PATH = "./themes/"


def findThemes(lookForCompiledResource=False):
    return Themes.findThemes(
        THEMES_PATH,
        lookForCompiledResource=lookForCompiledResource
    )


def compileThemes():
    themes = findThemes(lookForCompiledResource=False)
    for theme in themes:
        cmd = 'utils/rcc.sh {root} {qrc}'.format(
            root=theme.path,
            qrc=theme.icons
        )

        status = os.WEXITSTATUS(os.system(cmd))
        if status == 0:
            print('Compiled resource for theme', theme.key)
            return True
        print('Failed to compile resource for theme', theme.key)
        return False


def getTheme(themes, themeKey):
    """ Get single theme by key.

    @param themes: List with themes to pick from.
    @type themes: list

    @param themeKey: Key (dir name) of the theme to pick.
    @type themeKey: str
    """
    for theme in themes:
        if theme.key == themeKey:
            return theme
    return None


def getThemes(themeKey=None):
    """ Pick one or all valid theme(s) depending on whether 'themeKey' is None
    or not.

    This function is used when the 'key' argument is set from cli.

    @param themeKey: Key (dir name) of the theme to pick.
    @type themeKey: None or str
    """
    themes = findThemes()

    if themeKey is not None:
        # Select single theme
        theme = getTheme(themes, themeKey)
        if not theme:
            print('Theme \'{0}\' not found.'.format(themeKey))
            return []
        themes = [theme]

    return themes


def listThemes():
    """ Prints all valid available theme keys (dir names)
    """
    for theme in findThemes():
        print(theme.key)


def compileResource(root, qrc):
    cmd = 'utils/rcc.sh {root} {qrc}'.format(
        root=root,
        qrc=qrc
    )
    status = os.WEXITSTATUS(os.system(cmd))
    if status == 0:
        print('Compiled resource for theme', root)
        return True
    print('Failed to compile resource for theme', root)
    return False


def makeTheme(themeKey=None):
    """ Compile resource file for one or all themes.
    """
    themes = getThemes(themeKey)

    status = True
    for theme in themes:
        if not compileResource(theme.path, theme.icons):
            print(
                'Failed to compile resource for theme \'{0}\''
                .format(theme.key)
            )
            status = False

    return status


def printFilesForTheme(themeKey=None):
    """ Prints all theme files for a single theme (when 'themeKey' is not None
    else it will print all theme files for all themes. (Absolute paths)
    """
    themes = getThemes(themeKey)

    for theme in themes:
        if not theme:
            print('Theme \'{0}\' not found.'.format(themeKey))
            return False

        print(
            os.path.abspath(os.path.join(pwd, theme.iconsPath(compiled=True)))
        )
        print(os.path.abspath(os.path.join(pwd, theme.fullCssPath())))
        print(os.path.abspath(os.path.join(pwd, theme.failCssPath())))
        print(os.path.abspath(os.path.join(pwd, theme.resultsCssPath())))
        print(os.path.abspath(os.path.join(pwd, theme.path, 'manifest.json')))

    return True


argsParser = argparse.ArgumentParser(description="searx-qt themes tool")
subParsers = argsParser.add_subparsers(
    dest="cmd",
    help="Command",
    required=True
)
# list
listParser = subParsers.add_parser("list", help="List themes")
# make
makeParser = subParsers.add_parser("make", help="Make themes")
makeParser.add_argument(
    'key',
    help='Theme key (theme dir name)',
    type=str,
    default='all',
    nargs='?'
)
# files
filesParser = subParsers.add_parser("files", help="Get files for theme")
filesParser.add_argument(
    'key',
    help='Theme key (theme dir name)',
    type=str,
    default='all',
    nargs='?'
)


args = argsParser.parse_args()
if args.cmd == 'list':
    listThemes()

elif args.cmd == 'make':
    themeKey = None
    if args.key != 'all':
        themeKey = args.key
    if not makeTheme(themeKey):
        sys.exit(1)

elif args.cmd == 'files':
    themeKey = None
    if args.key != 'all':
        themeKey = args.key
    if not printFilesForTheme(themeKey):
        sys.exit(1)

sys.exit(0)
